<template>
  <div class="stock-list">
    <el-auto-resizer>
      <template #default="{ height, width }">
        <el-table-v2
          :columns="columns"
          :data="tableData"
          :width="width"
          :height="height"
          @column-sort="onSort"
          fixed
        />
      </template>
    </el-auto-resizer>

    <DetailStock
      v-if="showDetail"
      :info="stockInfo"
      @close="handleCloseDetail"
    />
  </div>
</template>

<script setup>
import { ref, h } from 'vue';
import { ElTag, ElButton } from 'element-plus';
import DetailStock from './DetailStock.vue';
import {
  formatMainMoney,
  getScoreColor,
  getRecommendation,
  getRecommendationType,
  calculateDealUI,
  calculateDeal,
  handleCopy
} from '../method/index.js';
import { detailStockHook } from '../commonHooks/index.js';
import hotConcept from '../store/hotConcept.js';
import { stockStore } from '@/store/stock';
const store = stockStore();

const { showDetail, stockInfo, handleOpenDetail, handleCloseDetail } =
  detailStockHook();

const tableData = ref([]);
const props = defineProps({
  data: {
    type: Array,
    required: true
  }
});
tableData.value = props.data;

const columns = [
  {
    key: 'code',
    dataKey: 'code',
    title: '股票代码',
    width: 120,
    fixed: true,
    cellRenderer: ({ cellData: code }) =>
      h(
        ElButton,
        {
          onClick: () => handleCopy(code),
          type: 'info',
          icon: 'DocumentCopy'
        },
        { default: () => code }
      )
  },
  {
    key: 'name',
    dataKey: 'name',
    title: '股票名称',
    width: 130,
    align: 'center',
    fixed: true,
    cellRenderer: ({ rowData }) =>
      h(
        ElButton,
        {
          onClick: () => handleOpenDetail(rowData)
        },
        { default: () => rowData.name }
      )
  },
  {
    key: 'sector',
    dataKey: 'sector',
    title: '所属板块',
    width: 180,
    cellRenderer: ({ rowData }) =>
      h('div', {}, rowData.sector ? `${rowData.sector}(${rowData.region})` : '')
  },
  {
    key: 'price',
    dataKey: 'price',
    title: '当前价格',
    sortable: true,
    align: 'center',
    width: 100
  },
  {
    key: 'changePercent',
    dataKey: 'changePercent',
    title: '涨跌幅',
    sortable: true,
    align: 'center',
    width: 100,
    cellRenderer: ({ rowData }) =>
      h('div', { style: { position: 'relative' } }, [
        h(
          'div',
          { class: rowData.changePercent >= 0 ? 'up-text' : 'down-text' },
          rowData.changePercent + '%'
        ),
        h(
          'div',
          {
            class: calculateStop(rowData)
              ? ''
              : rowData.changePercent >= 0
              ? 'stop-text stop-up'
              : 'stop-text stop-down',
            style: { position: 'absolute' }
          },
          formatStop(rowData)
        )
      ])
  },
  {
    key: 'mainMoneyNet',
    dataKey: 'mainMoneyNet',
    title: '主力净流入',
    sortable: true,
    align: 'center',
    width: 100,
    cellRenderer: ({ cellData: mainMoneyNet }) =>
      h(
        'span',
        { class: mainMoneyNet >= 0 ? 'up-text' : 'down-text' },
        formatMainMoney(mainMoneyNet)
      )
  },
  {
    key: 'transactionVolume',
    dataKey: 'transactionVolume',
    title: '成交额',
    sortable: true,
    align: 'center',
    width: 120,
    cellRenderer: ({ cellData: transactionVolume }) =>
      h('span', {}, formatTransactionVolume(transactionVolume))
  },
  {
    key: 'turnoverRate',
    dataKey: 'turnoverRate',
    title: '换手率',
    sortable: true,
    align: 'center',
    width: 120,
    cellRenderer: ({ cellData: turnoverRate }) =>
      h('span', {}, turnoverRate + '%')
  },
  {
    key: 'yieldRate',
    dataKey: 'yieldRate',
    title: '股息率',
    sortable: true,
    align: 'center',
    width: 100,
    cellRenderer: ({ cellData: yieldRate }) =>
      h('span', {}, Number(yieldRate) + '%')
  },
  {
    key: 'predictionScore',
    dataKey: 'predictionScore',
    title: '量化得分',
    sortable: true,
    align: 'center',
    width: 100,
    cellRenderer: ({ cellData: predictionScore }) =>
      h(
        'span',
        { style: { color: getScoreColor(predictionScore) } },
        Math.round(predictionScore) + '分'
      )
  },
  {
    key: 'predictionScore',
    dataKey: 'predictionScore',
    title: '量化结果',
    align: 'center',
    width: 100,
    cellRenderer: ({ cellData: predictionScore }) =>
      h(
        ElTag,
        {
          type: getRecommendationType(predictionScore),
          class: predictionScore >= 75 ? 'strong-prediction' : 'prediction'
        },
        () => {
          return getRecommendation(predictionScore);
        }
      )
  },
  {
    key: 'lowPrice',
    dataKey: 'lowPrice',
    title: '近4年高抛低吸',
    align: 'center',
    width: 120,
    cellRenderer: ({ rowData }) => {
      return h(
        'span',
        { class: calculateDealUI(rowData) },
        {
          default: () => {
            return calculateDeal(rowData);
          }
        }
      );
    }
  }
];

const sortState = ref({
  changePercent: 'asc',
  transactionVolume: 'asc',
  turnoverRate: 'asc',
  yieldRate: 'asc',
  price: 'asc',
  mainMoneyNet: 'asc',
  predictionScore: 'asc'
});
const onSort = ({ key }) => {
  store.updateSort(true);
  sortState.value[key] = sortState.value[key] === 'desc' ? 'asc' : 'desc';
  tableData.value = tableData.value.sort((a, b) => {
    if (sortState.value[key] === 'desc') {
      return b[key] - a[key];
    } else {
      return a[key] - b[key];
    }
  });
};

const formatAmount = (amount) => {
  if (!amount) return '0';
  return amount.toString().replace(/(?=(\B)(\d{3})+$)/g, ',');
};

const formatTransactionVolume = (amount) => {
  if (!amount || amount === '-') return '0';

  let result = {};
  let k = 10000;
  let units = ['', '万', '亿', '万亿'];
  let i = 0;
  if (amount < k) {
    result.value = amount;
    result.unit = units[i];
  } else {
    i = Math.floor(Math.log(amount) / Math.log(k));
    result.value = (amount / Math.pow(k, i)).toFixed(2);
    result.unit = units[i];
  }

  return result.value + result.unit;
};

const calculateConcept = (concept) => {
  let conceptList = concept.split(',') || [];

  for (const item of conceptList) {
    if (hotConcept.includes(item)) {
      return item;
    }
  }
  return conceptList[0];
};

const calculateStop = ({ code, changePercent }) => {
  if (
    code.startsWith('688') ||
    code.startsWith('300') ||
    code.startsWith('301')
  ) {
    if (Math.abs(changePercent) > 19.4) {
      return false;
    } else {
      return true;
    }
  } else {
    if (Math.abs(changePercent) > 9.4) {
      return false;
    } else {
      return true;
    }
  }
};

const formatStop = ({ code, changePercent }) => {
  if (
    code.startsWith('688') ||
    code.startsWith('300') ||
    code.startsWith('301')
  ) {
    if (Math.abs(changePercent) > 19.4) {
      return '停';
    } else {
      return '';
    }
  } else {
    if (Math.abs(changePercent) > 9.4) {
      return '停';
    } else {
      return '';
    }
  }
};
</script>

<style lang="scss" scoped>
.stock-list {
  width: 1400px;
  height: calc(100% - 40px);
  margin: 0 auto;
  position: relative;

  .icon-top {
    position: absolute;
    z-index: 100;
    right: -60px;
    bottom: 10px;
    font-size: 40px;
    cursor: pointer;
  }
}
</style>

<style lang="scss">
.stop-text {
  z-index: 1;
  top: -14px;
  right: -16px;
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  color: #fff;
}
.stop-up {
  background: #f40;
  border: 1px solid #f40;
}
.stop-down {
  background: #4f0;
  border: 1px solid #4f0;
}
</style>
